package vg.modules.zoom.components;

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;

import vg.services.graph_view_manager.interfaces.graph_view.AGraphView;
import vg.services.graph_view_manager.realization.graph_view.smart_graph_view.realization.actions.ZoomAction;

/**
 * This class realizes zoom in.
 * @author tzolotuhin
 */
public class ZoomOut {
	// Main components
	private final JButton button;
	// Data
	private AGraphView view;
	// Mutex
	private final Object generalMutex = new Object();
	/**
	 * Constructor.
	 */
	public ZoomOut() {
		// init components
		button = new JButton(new ImageIcon("./data/resources/textures/minusButton.png"));
		button.setToolTipText("Zoom out");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				zoomOut();
			}
		});
		button.setEnabled(false);
		// ctrl + minus
		KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {					
			public boolean dispatchKeyEvent(KeyEvent e) {
				// if use VK_MINUS, that it's will not work, because JDK has bug with it.
				if (e.getID() == KeyEvent.KEY_PRESSED && (e.getKeyChar() == '-' || e.getKeyCode() == KeyEvent.VK_MINUS) && e.isControlDown()) {
					zoomOut();
					return(true);
				}
				return(false);
			}
		});
	}

	public JComponent getView() {
		return(this.button);
	}

	/**
	 * This method changes current view.
	 */
	public void changeView(final AGraphView newView) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				synchronized (ZoomOut.this.generalMutex) {
					ZoomOut.this.view = newView;
					button.setEnabled(ZoomOut.this.view != null);
				}
			}
		});
	}
	///////////////////////////////////////////////////////////////////////////
	// PRIVATE METHOD
	///////////////////////////////////////////////////////////////////////////
	private void zoomOut() {
		synchronized (generalMutex) {
			if(view != null) {
				view.addAction(new ZoomAction(ZoomAction.ZOOM_OUT_ACTION));
			}
		}
	}
}
